<template>
  <div class="queryform-container">
    <a-form ref="queryFormRef" :model="queryForm" layout="inline" :label-col="{width:'100px'}">
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="项目编码"
                   name="projectCode">
        <a-select v-model:value="queryForm.projectCode" style="width: 150px">
          <a-select-option v-for="project in projectList" :value="project.projectCode">{{ project.projectName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="实体类名称"
                   name="className">
        <a-input v-model:value="queryForm.className" allow-clear/>
      </a-form-item>
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="表名称"
                   name="tableName">
        <a-input v-model:value="queryForm.tableName" allow-clear/>
      </a-form-item>
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="生成模块名"
                   name="moduleName">
        <a-input v-model:value="queryForm.moduleName" allow-clear/>
      </a-form-item>
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="生成业务名"
                   name="businessName">
        <a-input v-model:value="queryForm.businessName" allow-clear/>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">查询</a-button>
        <a-button class="split-button" type="primary" @click="handleReset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
  <div class="action-buttons-container">
    <a-button class="split-button" type="primary" @click="handleAdd">新增</a-button>
    <a-button class="split-button" type="primary" @click="handleOpenSql">从create语句解析</a-button>
    <a-button class="split-button" type="primary" :disabled="!singleSelect" @click="handleEdit(null)">修改
    </a-button>
    <a-popconfirm
        title="确定删除这条记录?"
        ok-text="确定"
        cancel-text="取消"
        @confirm="handleDelete(null)"
        :disabled="!singleSelect"
    >
      <a-button class="split-button" type="danger" :disabled="!singleSelect">删除</a-button>
    </a-popconfirm>
  </div>
  <a-table :data-source="sysGenModelList" :columns="columns" rowKey="id"
           :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
           :pagination="false"
  ></a-table>
  <div style="text-align: right;padding-top: 20px;padding-bottom: 20px;">
    <a-pagination @change="handlePageChange" :total="pagination.total" :page-size="pagination.pageSize"
                  :current="pagination.current"/>
  </div>
  <a-modal v-model:visible="showAddModel" style="width:1000px;" title="新增或修改表" @ok="handleSave">
    <a-tabs type="card">
      <a-tab-pane key="1" tab="基础信息">
        <a-form ref="addFormRef" :model="addForm"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }" autocomplete="off">
          <a-form-item style="display: none;"
                       label="id"
                       name="id">
            <a-input v-model:value="addForm.id"/>
          </a-form-item>
          <a-form-item style="display: none;"
              label="项目编码"
              name="projectCode"
              :rules="[{ required: false, message: '请输入项目编码' }]"
          >
            <a-input v-model:value="addForm.projectCode"/>
          </a-form-item>
          <a-form-item
              label="表名称"
              name="tableName"
              :rules="[{ required: false, message: '请输入表名称' }]"
          >
            <a-input v-model:value="addForm.tableName"/>
          </a-form-item>
          <a-form-item
              label="表中文名"
              name="tableComment"
              :rules="[{ required: false, message: '请输入表中文名' }]"
          >
            <a-input v-model:value="addForm.tableComment"/>
          </a-form-item>
          <a-form-item
              label="实体类名称"
              name="className"
              :rules="[{ required: false, message: '请输入实体类名称' }]"
          >
            <a-input v-model:value="addForm.className"/>
          </a-form-item>
          <a-form-item
              label="生成包路径"
              name="packageName"
              :rules="[{ required: false, message: '请输入生成包路径' }]"
          >
            <a-input v-model:value="addForm.packageName"/>
          </a-form-item>
<!--          <a-form-item-->
<!--              label="生成源码磁盘路径，相对于项目根路径"-->
<!--              name="generatePath"-->
<!--              :rules="[{ required: false, message: '生成源码磁盘路径' }]"-->
<!--          >-->
<!--            <a-input v-model:value="addForm.generatePath"/>-->
<!--          </a-form-item>-->
          <a-form-item
              label="所属模块"
              name="moduleName"
              :rules="[{ required: false, message: '请输入所属模块' }]"
          >
            <a-input v-model:value="addForm.moduleName"/>
          </a-form-item>
          <a-form-item
              label="功能名"
              name="businessName"
              :rules="[{ required: false, message: '请输入功能名' }]"
          >
            <a-input v-model:value="addForm.businessName"/>
          </a-form-item>
          <a-form-item
              label="功能名(中文描述)"
              name="functionName"
              :rules="[{ required: true, message: '请输入生成功能名(中文描述)' }]"
          >
            <a-input v-model:value="addForm.functionName"/>
          </a-form-item>
          <a-form-item
              label="作者"
              name="functionAuthor"
              :rules="[{ required: true, message: '请输入生成功能作者' }]"
          >
            <a-input v-model:value="addForm.functionAuthor"/>
          </a-form-item>
          <a-form-item
              label="权限前缀"
              name="permissionPrefix"
              :rules="[{ required: false, message: '请输入权限前缀' }]"
          >
            <a-input v-model:value="addForm.permissionPrefix"/>
          </a-form-item>
          <a-form-item
              label="备注"
              name="remark"
              :rules="[{ required: false, message: '请输入备注' }]"
          >
            <a-input v-model:value="addForm.remark"/>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" tab="表字段">
        <a-table :dataSource="addForm.propList" :pagination="false"
                 :columns="[
          {
            title: 'java字段名',
            dataIndex: 'javaField',
            key: 'javaField',
          },
          {
            title: '列名',
            dataIndex: 'columnName',
            key: 'columnName',
          },
          {
            title: '列注释',
            dataIndex: 'columnComment',
            key: 'columnComment',
          },
          {
            title: '列类型',
            dataIndex: 'columnType',
            key: 'columnType',
          },{
            title: 'java类型',
            dataIndex: 'javaType',
            key: 'javaType',
          },{
            title: '操作',
            dataIndex: 'action',
            key: 'action',
          },
        ]">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'javaField'">
              <a-input v-model:value="record.javaField"></a-input>
            </template>
            <template v-if="column.key === 'columnName'">
              <a-input v-model:value="record.columnName"></a-input>
            </template>
            <template v-if="column.key === 'columnComment'">
              <a-input v-model:value="record.columnComment"></a-input>
            </template>
            <template v-if="column.key === 'columnType'">
              <a-select v-model:value="record.columnType" style="width: 150px"
                        :options="[
                            {value:'INT'},
                            {value:'VARCHAR'},
                            {value:'BIGINT'},
                            {value:'DATETIME'},
                            {value:'DOUBLE'},
                            {value:'TEXT'},
                            {value:'LONGTEXT'},
                            ]"
              ></a-select>
            </template>
            <template v-if="column.key === 'javaType'">
              <a-select v-model:value="record.javaType" style="width: 150px"
                        :options="[
                            {value:'Integer'},
                            {value:'String'},
                            {value:'Long'},
                            {value:'Date'},
                            {value:'Double'},
                            ]"
              ></a-select>
            </template>
            <template v-if="column.key==='action'">
              <a-button danger @click="handleDeleteColumn(record)">
                <delete-outlined/>
                删除
              </a-button>
            </template>
          </template>
        </a-table>
        <div style="text-align: right;">
          <a-button style="margin-top:20px;" type="primary" @click="()=>{addForm.propList.push({})}">
            <template #icon>
              <plus-outlined/>
            </template>
            添加列
          </a-button>
        </div>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
  <a-modal v-model:visible="showSqlModel" title="从create sql语句创建表结构"
           @ok="handleSqlSave">
    <a-form ref="sqlFormRef" :model="sqlForm"
            autocomplete="off">
      <a-form-item
          label="项目"
          name="projectCode"
          :rules="[{ required: true, message: '请选择一个项目' }]"
      >
        <a-select v-model:value="sqlForm.projectCode" style="width: 150px">
          <a-select-option v-for="project in projectList" :value="project.projectCode">{{ project.projectName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
          label="create sql"
          name="sql"
          :rules="[{ required: true, message: '请输入create sql语句' }]"
      >
        <a-textarea style="height: 300px;" v-model:value="sqlForm.sql"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>

import {onMounted, reactive, ref, unref} from "vue";
import request from '@/util/request.js'
import {message} from "ant-design-vue";
import {showLoading,hideLoading, validValue} from "@/util/util.js";

let showAddModel = ref(false)
let addModelTitle = ref("新增")
let queryForm = reactive({})
let sysGenModelList = ref([])
let singleSelect = ref(false)
let selectedRowKeys = ref([])
let selectedRows = ref([])
let addForm = ref({propList:[]})
let sqlForm = ref({sql: ''})
const projectList = ref([]);
let pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
})
const queryFormRef = ref(null);
let addFormRef = ref(null);
const columns = [
  {
    title: '表名称',
    dataIndex: 'tableName',
    key: 'tableName',
  }, {
    title: '表中文名',
    dataIndex: 'tableComment',
    key: 'tableComment',width:100
  },
  {
    title: '实体类名称',
    dataIndex: 'className',
    key: 'className',
  },
  {
    title: '所属模块',
    dataIndex: 'moduleName',
    key: 'moduleName',
  },
  {
    title: '功能名',
    dataIndex: 'businessName',
    key: 'businessName',
  },
  {
    title: '功能名(中文描述)',
    dataIndex: 'functionName',
    key: 'functionName',
  },
  {
    title: '生成功能作者',
    dataIndex: 'functionAuthor',
    key: 'functionAuthor',
  },
  {
    title: '权限前缀',
    dataIndex: 'permissionPrefix',
    key: 'permissionPrefix',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
  },
  {
    title: '生成包路径',
    dataIndex: 'packageName',
    key: 'packageName',
  },
  // {
  //   title: '生成源码磁盘路径',
  //   dataIndex: 'generatePath',
  //   key: 'generatePath',
  // },
]
onMounted(() => {
  handleQuery()
  //加载项目列表
  request({
    method: 'post',
    url: '/api/system/gen/project/list',
    data: {}
  }).then((response) => {
    hideLoading()
    const list = response.data;
    projectList.value = list;
  });
})
const handleQuery = () => {
  let queryParam = {...queryForm};
  queryParam["currentPage"] = pagination.value.current
  queryParam["pageSize"] = pagination.value.pageSize
  query(queryParam)
}

function handleReset() {
  queryFormRef.value.resetFields();
  handleQuery()
}

const query = (param) => {
  showLoading()
  //请求后端
  request({
    method: 'post',
    url: '/api/system/gen/model/page',
    data: param
  }).then((response) => {
    hideLoading()
    let pager = response.data;
    sysGenModelList.value = pager.rows;
    pagination.value.current = pager.currentPage
    pagination.value.pageSize = pager.pageSize
    pagination.value.total = pager.totalCount
  });
}
const handlePageChange = (current) => {
  pagination.value.current = current
  handleQuery()
}

function handleSave() {
  addFormRef.value.validate().then((res) => {
    res.propList=addForm.value.propList;
    showLoading()
    request({
      method: 'post',
      url: '/api/system/gen/model/addOrUpdate',
      data: res
    }).then((res) => {
      hideLoading()
      if (res.code === 200) {
        showAddModel.value = false;
        message.success("保存成功")
        handleQuery();
      } else {
        message.error("操作失败" + res.errMsg)
      }
    })
  }).catch(() => {
    hideLoading()
  })
}

function handleAdd() {
  //新增
  addModelTitle.value = '新增'
  showAddModel.value = true
  addForm.value = {propList:[]};
}

const showSqlModel = ref(false);

function handleOpenSql() {
  showSqlModel.value = true
}

function handleSqlSave() {
  showLoading()
  request({
    method: 'post',
    url: '/api/system/gen/model/createBySql',
    params: unref(sqlForm)
  }).then((res) => {
    hideLoading()
    console.log(res)
  })
}

function handleEdit(row) {
  showAddModel.value = true
  addModelTitle.value = '修改'
  //加载数据
  if (!validValue(row)) {
    row = selectedRows.value[0];
  }
  addForm.value = {};
  showLoading()
  request({
    method: 'get',
    url: '/api/system/gen/model/getModelInfoById',
    params: {id: row.id}
  }).then((res) => {
    hideLoading()
    addForm.value = res.data
  })
}

function handleDelete(row) {
  if (!validValue(row)) {
    row = selectedRows.value[0];
  }
  showLoading()
  request({
    method: 'delete',
    url: '/api/system/gen/model/deleteById',
    params: {id: row.id}
  }).then((res) => {
    hideLoading()
    if (res.code === 200) {
      message.info('删除成功');
      handleQuery()
    } else {
      message.error("删除失败")
    }
  })
}

function onSelectChange(rowKeys, rows) {
  selectedRowKeys.value = rowKeys
  selectedRows.value = rows
  singleSelect.value = rowKeys && rowKeys.length === 1
}

//删除表的一列
function handleDeleteColumn(col) {
  const index = addForm.value.propList.indexOf(col);
  addForm.value.propList.splice(index, 1);
}

function activated() {
  console.log('activated');
}
</script>
